package com.guodi.map.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.guodi.common.constant.StatusCode;
import com.guodi.common.utils.HttpRequester;
import com.guodi.common.utils.HttpRespons;
import com.guodi.core.boot.ctrl.BaseController;
import com.guodi.core.tool.api.R;
import com.guodi.map.service.IMapLayerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

/**
 * @描述：地图配置控制类
 * @作者: 陈玉安
 * @日期: 2019-09-11
 */
@RestController
@RequestMapping("/MapConfig")
@Api(value = "API - InfoMapServiceController", tags="地图配置接口")
public class MapConfigController extends BaseController {

    @Autowired
    private IMapLayerService mapLayerService;

    /**
    * @描述: 获取地图配置
    * @作者: 陈玉安
    * @日期: 2019-09-011
    **/
    @PostMapping("/getConfig")
    @ApiOperation(value = "获取地图配置")
    public R getConfig(){
        List<Map> list = JSONArray.parseArray("[{\n" +
                "            \"map_refernce\":\"2361\",\n" +
                "            \"map_scales\":\"500000,250000,125000,64000,32000,16000,8000,4000, 2000,1000\",\n" +
                "            \"zoom_solutions\":\"132.29193125052919, 66.145965625264594, 33.072982812632297, 16.933367200067735,8.4666836000338677,4.2333418000169338,2.1166709000084669,1.0583354500042335,0.52916772500211673,0.26458386250105836\",\n" +
                "            \"map_zoom\":0,\n" +
                "            \"name\":\"智能编制一张图\",\n" +
                "            \"map_extent\":\"37311166.716210537,2340378.5809470066, 37509734.823564149,2454552.066450261\",\n" +
                "            \"map_xy\":\"37410450.76988734,2397465.323698634\"\n" +
                "    },{\n" +
                "      \"map_refernce\": \"4547\",\n" +
                "      \"map_scales\": \"500000,250000,125000,64000,32000,16000,8000,4000,2000,1000,500\",\n" +
                "      \"zoom_solutions\": \"132.29193125052919,66.145965625264594,33.072982812632297, 16.933367200067735,8.4666836000338677, 4.2333418000169338,2.1166709000084669,1.0583354500042335,0.52916772500211673,0.26458386250105836,0.13229193125052918\",\n" +
                "    \"map_extent\":\"469984.79679999966,2462646.0447000004,570636.38300000038,2533257.3228999991\",\n" +
                "      \"name\": \"空间规划一张图\",\n" +
                "      \"map_zoom\": 1,\n" +
                "      \"map_xy\": \"520310.5899,2497951.6837999998\"\n" +
                "    }]", Map.class);
        return R.data(list);
    }

    public static final String PROXY_URI = "proxyServer/layer/";

    /**
    * @描述: 专题制作接口转发
    * @作者: 代鹏刚
    * @日期: 2020/2/27 17:12
    **/
    @RequestMapping(value = "/proxy", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "专题制作接口转发")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "url", value = "请求url", required = true, dataType = "String"),
        @ApiImplicitParam(name = "param", value = "参数",dataType = "String"),
    })
    public R proxy(@RequestBody Map<String,String> paras) throws UnsupportedEncodingException {
        String param = paras.get("param").toString();
        param = URLDecoder.decode(param, "UTF-8");
        String url = paras.get("url").toString();
        if(StringUtils.isBlank(url)){
            return R.fail(StatusCode.ERROR_CODE_40005,"入参url不能为空");
        }
        if(StringUtils.isNotBlank(param)){
            // 2021-01-29
            // 汤厚韬注：由于前端参数值里含有>(大于号),<(小于号)，在经过网关转发后，后台接受的param的值已经完全错乱，故暂时性的采取前端传转义字符，后台再反转义出来
            param = StringEscapeUtils.unescapeXml(param);
            Map<String, String> params = (Map<String, String>) JSONObject.parse(param);
            // 还原代理图层链接
            if (param.contains(PROXY_URI)) {
                String mapJson = params.get("Web_Map_as_JSON");
                if (StringUtils.isNotBlank(mapJson)) {
                    JSONObject mapObj = JSONObject.parseObject(mapJson);
                    JSONArray mapArr = (JSONArray) mapObj.get("operationalLayers");
                    if (mapArr != null) {
                        for (JSONObject item: mapArr.toJavaList(JSONObject.class)) {
                            String layerUrl = item.getString("url");
                            if (StringUtils.isNotBlank(layerUrl) && layerUrl.contains(PROXY_URI)) {
                                String layerId = layerUrl.substring( layerUrl.indexOf(PROXY_URI) + PROXY_URI.length());
                                if (layerId.contains("/")) {
                                    layerId = layerId.substring(0, layerId.indexOf("/"));
                                }
                                String originalUrl = mapLayerService.getLayerUrlById(layerId);
                                mapJson = mapJson.replace(layerUrl, originalUrl);
                            }
                        }
                    }
                    params.put("Web_Map_as_JSON", mapJson);
                }

            }
            HttpRequester requester = new HttpRequester();
            HttpRespons respons = null;
            try {
                respons = requester.sendPost(url, params);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(respons != null){
                return R.data(respons.getContent());
            }
        }
        return R.data(null);
    }
}
